import numpy as np
import pandas as pd
from scipy.spatial.distance import mahalanobis

class MahalanobisDistance:
    def __init__(self, data=None, url=None):
        if url:
            data_set = pd.read_excel(url)
            self.data_set = np.array(data_set)
        else:
            self.data_set = np.array(data)

        # 计算协方差矩阵
        self.cov = np.cov(self.data_set, rowvar=False)
        self.cov_inv = np.linalg.inv(self.cov)
        # 计算各特征平均值
        self.avg = np.average(self.data_set, axis=0)

    # 计算点到数据集的马氏距离
    def MahaDist(self, point):
        return mahalanobis(point, self.avg, self.cov)

    def allMahaDist(self):
        dist_array = []
        for i in range(len(self.data_set)):
            dist_array.append([mahalanobis(self.data_set[i], self.avg, self.cov_inv)])
        return dist_array


if __name__ == '__main__':
    # 存放判断矩阵的文件地址
    path = 'Maha_dist_data.xlsx'
    Maha_model = MahalanobisDistance(url=path)
    # dist = Maha_model.MahaDist(data_set[5])
    dist_array = Maha_model.allMahaDist()
    # print(dist)
    print(dist_array)